<?php

namespace App\Http\Controllers\H5\Login;

use App\Enum\enum_wechat;
use App\Http\Controllers\Api\ApiBaseController;
use App\Http\Controllers\H5\H5BaseController;
use App\Http\Format\FormatBase;
use App\Models\CityChinaModel;
use App\Models\ConfigModel;
use App\Models\GoodsModel;
use App\Models\OrderModel;
use App\Models\PetsModel;
use App\Models\TableItemModel;
use App\Models\TableModel;
use App\Models\TagsModel;
use App\Models\TokenModel;
use App\Models\ToUserTaskModel;
use App\Models\UserAreaLogsModel;
use App\Models\UserMessageModel;
use App\Models\UserModel;
use App\Models\UserMsmLogsModel;
use App\Models\UserPublicModel;
use App\Models\UserSignModel;
use App\Models\UserTokenModel;
use App\Services\Api\UserService;
use App\Services\CurlBasiceService;
use App\Tools\AliyunSmsTool;
use App\Tools\AliyunUploadTool;
use App\Tools\WechatPhone;
use Illuminate\Http\Request;
use Exception;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class UserController extends H5BaseController
{
    /**
     * 使用code，获取openid，返回token
     * @param Request $request
     * @return object|null
     * @throws Exception
     */
    public function auth_code(Request $request):?object
    {
        $params = $request->only(['code', 'share_token']);

        $wxxcx_config = config('wechat.wxxcx_h5');
        //拼接参数
        $realUrl = enum_wechat::WEB_USER_AUTHOR;
        $realUrl = str_replace("CODE", $params['code'] ?? '', $realUrl);
        $realUrl = str_replace("APPID", $wxxcx_config['app_id'] ?? '', $realUrl);
        $realUrl = str_replace("SECRET", $wxxcx_config['app_secret'] ?? '', $realUrl);
        //curl请求
        $result = CurlBasiceService::getInstance()->httpGet($realUrl);

        //数据库操作，返回token
        $token = UserService::getInstance()->getUserCodeH5(json_decode($result, true), $params['share_token'] ?? '');


        if (empty($token[0])){
            return $this->codeError([], 1011, '参数错误');
        }

        //获取access_token
        $accessToken = TokenModel::getSingle();

        return $this->codeSuccess([
            'token'=>$token[0],
            'access_token'=>$accessToken['token'] ?? ''
        ]);

    }

    /**
     * 用户详情
     * @param Request $request
     * @return object|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function init(Request $request):?object
    {
        $userOne = adminH5User();

        //获取access_token
        $accessToken = TokenModel::getSingle();

        $userOne['area_province_msg'] = $this->handleCity($userOne['area_province_id']);
        $userOne['area_city_msg'] = $this->handleCity($userOne['area_city_id']);
        $userOne['area_district_msg'] = $this->handleCity($userOne['area_district_id']);

        return $this->codeSuccess([
            'token'=> $request->header('token'),
            'access_token'=>$accessToken['token'] ?? '',
            'data'=> $userOne
        ]);
    }

    public function handleCity($params_city){
        $temp_name = '';
        if (!empty($params_city)){
            $area_province_id = CityChinaModel::getSingle(['code'=>$params_city]);
            if ($area_province_id['name']){
                $temp_name = $area_province_id['name'];
            }
        }

        return $temp_name;
    }

    /**
     * 填充用户信息
     * @param Request $request
     * @return object|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function fill_user_data(Request $request):?object
    {
        $params = $request->only(['mobile', 'area_province_id', 'area_city_id', 'area_district_id', 'head_img_url', 'nickname', 'is_admin']);

        if (empty($params['is_admin'])){
            //判断修改时间
            $res = UserAreaLogsModel::getUserAll(['user_id'=>  adminH5User('id'), ['created_at', '>', time()-(86400*365)]]);

            if (count($res) >= 2){
                return $this->codeError([], 1011, '每年只能修改2次');
            }

            $res1 = UserAreaLogsModel::getUserAll(['user_id'=>  adminH5User('id'), ['created_at', '>', time()-(86400*90)]]);
            if (count($res) >= 1){
                return $this->codeError([], 1011, '每季度只能修改1次');
            }

            //记录日志
            UserAreaLogsModel::insertSingle([
                'created_at'=> time(),
                'user_id'=> adminH5User('id')
            ]);
        }
        unset($params['is_admin']);

        //数据库操作
        UserService::getInstance()->dealtUserData($params);

        return $this->codeSuccess();
    }

    /**
     * @param $params
     * @param $field
     * @return bool
     */
    public function handleIsNull($params, $field): bool
    {
        foreach ($field as $value){
            if (empty($params[$value])){
                return false;
            }

        }

        return true;
    }


    public function handlePreview($tableId, $publicContent)
    {
        //根据信息类型id获取，模板编号
        $info = TableModel::getOneById($tableId, '*');
        $info['content_insert'] = json_decode($info['content_insert'], true);

        if (empty($info['msg'])){
            return false;
        }

        $tmp = enum_wechat::TEMP;
        $infoMsg = $tmp[$info['msg']];

        $list = array_column($publicContent, null, 'id');

        //根据title换参数
        if (!empty($info['content_insert']['title'])){
            foreach ($info['content_insert']['title'] as $keys => $value){
                $artTemp = '';
                foreach ($value as $vs){
                    if (!empty($list[$vs]['content'])){
                        $artTemp .= ',' . $list[$vs]['content'];
                    }
                }
                $artTemp = trim($artTemp, ',');
                $infoMsg = str_replace("TITLE" . ($keys + 1), $artTemp ?? '', $infoMsg);

            }
        }

        //根据content换参数
        if (!empty($info['content_insert']['content'])){
            foreach ($info['content_insert']['content'] as $keys => $value){
                $artTemp = '';
                foreach ($value as $vs){
                    if (!empty($list[$vs]['content'])){
                        $artTemp .= ',' . $list[$vs]['content'];
                    }
                }
                $artTemp = trim($artTemp, ',');
                $infoMsg = str_replace("CONTENT" . ($keys + 1), $artTemp ?? '', $infoMsg);

            }
        }

        return $infoMsg;
    }

    /**
     * 刷新信息列表
     * @return void
     */
    public function refresh_message(Request $request): ?object
    {
        $params = $request->only(['no', 'cat_1', 'admin_id', 'page', 'limit', 'url_code']);

        $where = [];
        if (!empty($params['no'])){
            $where['no'] =  $params['no'];
        }

        if (!empty($params['cat_1'])){
            $where['cat_1'] =  $params['cat_1'];
        }

        if (!empty($params['admin_id'])){
            $where['admin_id'] =  $params['admin_id'];
        }

        $whereInKey = '';
        $whereInValue = [];
        if (!empty($params['url_code'])){
            //获取 ToUserTaskModel 数据
            $to_user_task = ToUserTaskModel::getSingle(['url_code'=> $params['url_code']]);
            if (empty($to_user_task['ids'])){
                return $this->codeError([], 1011, '链接已失效');
            }

            $whereInKey = 'id';
            $whereInValue = json_decode($to_user_task['ids'], true);
        }else{
            $where['user_id'] =  adminH5User('id');
        }
        $where[] =  ['status', '>', 0];

        if(empty($whereInValue)){
            return $this->codeError([], 1011, '该任务没有数据');
        }

        $userList = UserPublicModel::getPage($where, $params['limit'] ?? 15, '*', $whereInKey, $whereInValue);

        $list = [];
        foreach ($userList['data'] as $value){
            unset($temp);
            $temp['id'] = $value['id'] ?? '';
            $temp['no'] = $value['no'] ?? '';
            $temp['style'] = $value['style'] ?? '';
            $temp['pay_num'] = $value['pay_num'] ?? '';
            $temp['rpc_id'] = $value['rpc_id'] ?? '';
            $temp['create_lxr_name'] = $value['create_lxr_name'] ?? '';
            $temp['create_lxr_mobile'] = $value['create_lxr_mobile'] ?? '';
            $temp['create_title'] = $value['create_title'] ?? '';
            $temp['plain_end_time'] = $value['plain_end_time'] ?? '';
            $temp['admin_name'] = '';
            $temp['created_at'] = date('Y-m-d H:i:s', $value['created_at']) ?? '';

            $temp_cat_msg = [];
            if (!empty($value['cat_1'][0]['name'])){
                $temp_cat_msg[] = $value['cat_1'][0]['name'];
            }

            if (!empty($value['cat_2'][0]['name'])){
                $temp_cat_msg[] = $value['cat_2'][0]['name'];
            }

            $temp['cat_msg'] = implode(',', $temp_cat_msg);

            if (!empty($value['admin_name'][0]['nickname'])){
                $temp['admin_name'] = $value['admin_name'][0]['nickname'];
            }

            $list[] = $temp;
        }
        $userList['data'] = $list;

        return $this->codeSuccess(FormatBase::listData($userList));
    }

    /**
     * 刷新信息列表-点击刷新
     * @param Request $request
     * @return object|null
     */
    public function refresh_click(Request $request): ?object
    {
        $params = $request->only(['id']);

        $bool = $this->handleIsNull($params, ['id']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');

        }

        foreach ($params['id'] as $value){
            UserPublicModel::addIncrementValue(['id'=> $value], 'refresh_times', 1, '', [], ['refresh_at'=> time()]);

        }
        return $this->codeSuccess();

    }



    public function message_update_data(Request $request): ?object
    {
        $params = $request->only(['id']);

        $bool = $this->handleIsNull($params, ['id']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');

        }

        //获取消息详情
        $messageInfo = UserMessageModel::getOneById($params['id'], '*');

        if (empty($messageInfo['table_id']) || empty($messageInfo['user_public_id'])){
            return $this->codeError([], 1011, '数据错误');

        }

        //获取用户发布的内容
        $publicInfo = UserPublicModel::getOneById($messageInfo['user_public_id'], '*');
        $contentList = [];
        if (!empty($publicInfo['content'])){
            $contentList = array_column(json_decode($publicInfo['content'], true), null, 'id');

        }

        //获取表单item
        $tableInfo = TableModel::getOneById($messageInfo['table_id'], '*');
        if (empty($tableInfo['content'])){
            return $this->codeError([], 1011, '数据错误');

        }

        //获取表单的item
        $itemList = TableItemModel::getUserData([], 'id', json_decode($tableInfo['content'], true));

        //循环表单，插入用户发布的内容
        foreach ($itemList as &$value){
            if (!empty($contentList[$value['id']])){
                $value['content'] = $contentList[$value['id']]['content'];
                $value['field'] = $contentList[$value['id']]['field'];
            }else{
                $value['content'] = '';
                $value['field'] = '';
            }
        }


        //返回
        return $this->codeSuccess($itemList);

    }

    /**
     * 首页-任务详情
     * @return void
     */
    public function task_detail(Request $request): ?object
    {
        $params = $request->only(['id']);
        if (empty($params['id'])){
            return $this->codeError([], 1011, '参数错误');
        }

        $public = UserPublicModel::getSingle(['id'=> $params['id']]);

        $public['cat_1_msg'] = '';
        if (!empty($public['cat_1'][0]['name'])){
            $public['cat_1_msg'] = $public['cat_1'][0]['name'];
        }

        $public['cat_2_msg'] = '';
        if (!empty($public['cat_2'][0]['name'])){
            $public['cat_2_msg'] = $public['cat_2'][0]['name'];
        }

        //地区
        //发布地区
        $public['area_json_msg'] = [];
        if (!empty($public['area_json'])){
            $public['area_json'] = json_decode($public['area_json'], true);
            $citu_ids = [];
            if (!empty($public['area_json']) && is_array($public['area_json'])){
                foreach ($public['area_json'] as $vs_1){
                    foreach ($vs_1 as $vs_2){
                        $citu_ids[] = $vs_2;
                    }
                }

                $city_all = CityChinaModel::getUserData([], 'code', $citu_ids);
                $city_all = array_column($city_all, null,'code');

                foreach ($public['area_json'] as $vs_1){
                    $public_city = [];
                    foreach ($vs_1 as $vs_2){
                        if (!empty($city_all[$vs_2]['name'])){
                            $public_city[] = $city_all[$vs_2]['name'];
                        }
                    }
                    $public['area_json_msg'][] = $public_city;
                }
            }else{
                $public['area_json_msg'] = [];
            }
        }

        if (!empty($public['tag_json'])){
            $public['tag_json'] = json_decode($public['tag_json'], true);
        }else{
            $public['tag_json'] = [];
        }

        if (!empty($public['content'])){
            $public['content'] = json_decode($public['content'], true);
        }else{
            $public['content'] = [];
        }

        unset($public['cat_1'], $public['cat_2']);

        return $this->codeSuccess($public);
    }
}
